package com.zh.file.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

/**
 * @Description:
 * @ClassName MyThreadPool
 * @date: 2021.01.15 09:54
 * @Author: zhanghang
 */
@Configuration
@EnableAsync // 使用注解开启多线程
public class MyThreadPool {

    @Bean("threadPool")
    public Executor createThreadPool(){
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                5,5,1,
                TimeUnit.SECONDS,new SynchronousQueue<Runnable>());
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(5); // 设置核心线程数
        threadPoolTaskExecutor.setMaxPoolSize(5); // 设置最大线程数
        threadPoolTaskExecutor.setKeepAliveSeconds(100);
        return threadPoolExecutor;
    }

    @Bean("threadPoolTask")
    public Executor createThreadPoolTask(){
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        //设置核心线程数
        threadPool.setCorePoolSize(10);
        //设置最大线程数
        threadPool.setMaxPoolSize(100);
        //线程池所使用的缓冲队列
        threadPool.setQueueCapacity(10);
        //等待任务在关机时完成--表明等待所有线程执行完
        threadPool.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时间 （默认为0，此时立即停止），并没等待xx秒后强制停止
        threadPool.setAwaitTerminationSeconds(60);
        //  线程名称前缀
        threadPool.setThreadNamePrefix("threadPoolTask-Async-");
        // 初始化线程
        threadPool.initialize();
        return threadPool;
    }
}
